import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Store from '../store'
import NotFound from '../views/404Notfound.vue'

Vue.use(VueRouter)
Vue.use(Store)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'User',
    redirect: 'user/center',
    component: () => import( /* webpackChunkName: "user" */ '../views/User.vue'),
    children: [
      {
        path: 'center',
        name: 'Center',
        component: () => import( /* webpackChunkName: "center" */ '../components/user/Center.vue')
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import( /* webpackChunkName: "order" */ '../views/Order.vue')
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import( /* webpackChunkName: "cart" */ '../components/user/Cart.vue')
      },
      {
        path: 'safe',
        name: 'Safe',
        component: () => import( /* webpackChunkName: "safe" */ '../components/user/Safe.vue')
      },
    ]
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import( /* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import( /* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/details/:id',
    name: 'Details',
    component: () => import( /* webpackChunkName: "free" */ '../views/Details.vue')
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound,
  },

]

const router = new VueRouter({
  // mode: 'history', // 历史记录
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user/center'  ) {
    // 当用户要跳转路由到 /user时，判断是否登录
    // 必须有token
    let token = localStorage.getItem('x-auth-token')
    if(token){
      next()
    }else{
      // 提示
      let obj = {content: "请先登录!", icon: "info"}
      Store.dispatch('AsyncToast', obj)
    }
    return 
  }
  next()
})

export default router
